package com.example.pageradapterdemo.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.pageradapterdemo.NewsDetailsActivity;
import com.example.pageradapterdemo.R;
import com.example.pageradapterdemo.adapter.NewsAdapter;
import com.example.pageradapterdemo.model.News;
import com.example.pageradapterdemo.util.Constants;


import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SimpleFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SimpleFragment extends Fragment {
    private static final String KEY_TYPE_ID = "typeId";
    public static final String KEY_NEWS_ID = "newsId";
    private static final OkHttpClient httpClient;
    public static final String NEWS_LIST_URL = "/news/list?typeId={typeId}&page=1";
    private NewsAdapter adapter;
    private int typeId;
    private RecyclerView recyclerView;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int what = msg.what;
            switch (what) {
                case 0x001:
                    List<News> newsList = (List<News>) msg.obj;
                    adapter.setList(newsList);
                    break;
            }
            return true;
        }
    });
    static{
        httpClient = new OkHttpClient();
    }
    public SimpleFragment() {
        // Required empty public constructor
    }
    public static SimpleFragment newInstance(int typeId) {
        SimpleFragment fragment = new SimpleFragment();
        Bundle args = new Bundle();
        args.putInt(KEY_TYPE_ID, typeId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            typeId = getArguments().getInt(KEY_TYPE_ID,0);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_simple, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        adapter = new NewsAdapter(R.layout.adapter_news_item);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setAdapter(adapter);
        loadNewsContentByTypeId(typeId);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                News news = (News) adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putString(KEY_NEWS_ID,news.getNewsId());
                Intent intent = new Intent(getContext(), NewsDetailsActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    private void loadNewsContentByTypeId(int typeId){
        String newsUrl = Constants.BASE_API.concat(NEWS_LIST_URL).replace("{typeId}",Integer.toString(typeId));
        Log.e("newsUrl",newsUrl);
        Request request = new Request.Builder()
                .url(newsUrl)
                .addHeader("app_id",Constants.APP_ID)
                .addHeader("app_secret",Constants.APP_SECRET)
                .build();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        String responseText = response.body().string();
                        JSONObject jsonObject = JSONObject.parseObject(responseText);
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        if (jsonArray != null) {
                            List<News> newsList = new ArrayList<>();
                            for (Object o : jsonArray) {
                                News news = JSONObject.parseObject(o.toString(),News.class);
                                newsList.add(news);
                            }
                            Message message = Message.obtain();
                            message.what = 0x001;
                            message.obj = newsList;
                            handler.sendMessage(message);

                        }
                    }

                }
            }
        });
    }
}